package com.fxu.docx2md.util;

import cn.hutool.core.util.StrUtil;
import com.fxu.docx2md.dto.TocTree;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文档处理工具类
 * @author fangxu
 * @version 1.0.0
 */
@Slf4j
public class DocxUtil {
    public static TocTree getTocTree(String file) {
        TocTree tree = new TocTree();
        List<IBodyElement> elements = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file);
             XWPFDocument document = new XWPFDocument(fis)) {

            boolean isToc = false;
            for (IBodyElement element : document.getBodyElements()) {
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph paragraph = (XWPFParagraph) element;
                    if (!isToc && isTocStart(paragraph.getText())) {
                        isToc = true;
                    }
                    if (isToc) {
                        if (StrUtil.isEmpty(paragraph.getText().replace(" ", ""))) {
                            break;
                        }
                        elements.add(element);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (IBodyElement element : elements) {
            XWPFParagraph paragraph = (XWPFParagraph) element;
            System.out.println(paragraph.getText() + "," + paragraph.getStyle());
        }
        return tree;
    }

    public static boolean isTocStart(String text) {
        return text.replace(" ", "").equals("目录");
    }
}